package com.nariano.server.domain.engine.droolsimpl;

import java.util.List;
import java.util.Random;
import java.util.logging.Logger;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.nariano.server.domain.entities.Area;
import com.nariano.server.domain.entities.Population;
import com.nariano.server.domain.entities.User;
import com.nariano.server.publisher.ClientPublisher;
import com.nariano.server.publisher.events.PopulationChanged;
import com.nariano.server.services.mapservice.MapService;
import com.nariano.server.services.statistics.PopulationDistribution;
import com.nariano.server.services.statistics.StatsService;
import com.nariano.server.services.userservice.UserService;

/**
 * Abstraction of production and consumption of resources
 * during a round
 */
public class ResourceManagementAction {
	
	public static final int MAX_RESOURCES_FACTOR = 10;

	private static final int STARVATION_LEVEL = -1;

	Logger logger = Logger.getLogger(ResourceManagementAction.class.getCanonicalName());
	
	@Autowired
	@Qualifier(value = "userService")
	private UserService userService;
	
	@Autowired
	@Qualifier(value = "statsService")
	private StatsService statsService;
	
	@Autowired
	@Qualifier(value = "mapService")
	private MapService mapService;

	@Autowired
	@Qualifier(value = "resourceCreator")
	private ResourceCreator resourceCreator;
	
	@Autowired
	@Qualifier(value="clientPublisher")
    ClientPublisher clientPublisher;
	
	private static Random  RAND = new Random();
	public void updateResources() {
		List<User> users = userService.getAllUsers();
		for(User user : users) {
			PopulationDistribution distr = statsService.getPopulationDistribution(user);
			int created = resourceCreator.create(distr);
			int consumed = resourceCreator.consume(distr);
			
			int delta = created - consumed;
			
			// Update user
			user.addResources(delta);
			if (user.getResources()<STARVATION_LEVEL) {
				user.setResources(STARVATION_LEVEL);
			} else if (user.getResources()> MAX_RESOURCES_FACTOR * distr.getPoupulationCount()) {
				user.setResources(10*distr.getPoupulationCount());
			}
			userService.updateUser(user);
			
			// If less that zero -> starvation
			if (user.getResources()<0) {
				//todo starve, remove one random users
				Population starvedToDeath = mapService.moveOutRandomPopulation(user.getId());
				logger.fine("Starvation at user " + user.getUserName() + " of " + starvedToDeath);
			}
			
			
		}
	}

}
